import {getUserInfo,updateUserBirthday} from "../../api/userInfo"
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate:new Date().getTime(),
    minDate: new Date().getTime(),
    showBirthdayPopup:false,
    showLogout:false,
    confirmPhoneNumber:"",
    userInfo:Object,
    gender:String,
    phoneNumber:String
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  async onShow(){
    let userInfo = await getUserInfo()
    // console.log(userInfo);
    let {gender,phoneNumber,birthday} = userInfo

    if(userInfo.gender === 0){
      gender = "女"
    }else if(userInfo.gender === 1){
      gender = "男"
    }else {
      gender = "保密"
    }

    let phoneNumberPart = phoneNumber.slice(0,3) + "****" + phoneNumber.slice(7,11) 
    
    this.setData({
      userInfo,
      gender,
      phoneNumberPart,
      phoneNumber:userInfo.phoneNumber,
      showBirthday:birthday.length == 0 ? true : false,
      birthday,
      imageUrl:userInfo.imageUrl + Math.random()
    })
  },

  toImagePage(){
    wx.navigateTo({
      url: '/pages/showUserInfo/image/index',
    })
  },

  // 选择生日
  chooseBirthday(){
    let {showBirthday} = this.data
    if(showBirthday){
      this.setData({
        showBirthdayPopup:true
      })
    }
  },
  // 取消填写生日
  cancelBirthdayPopup(){
    this.setData({
      showBirthdayPopup:false
    })
  },

  // 提交生日
  async confirmBirthday(event){
    let timestamp = event.detail // 时间戳
    let date = new Date(timestamp)
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()

    let ret = await updateUserBirthday(year+"年"+month+"月"+day+"日")
    console.log(ret);

    if(ret.code === 200){
      this.setData({
        showBirthdayPopup:false,
        showBirthday:false,
      })
      this.onShow()
    }
  },

  // 显示注销时的对话框
  logout(){
    wx.showModal({
      title: '您的账号将被注销，是否继续?',
      complete: (res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          this.setData({
            showLogout:true
          })
        }
      }
    })
  },

  onClose(){
    this.setData({
      showLogout:false
    })
  },

  // 确认注销
  submit(){
    let {confirmPhoneNumber,phoneNumber} = this.data

    if(/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(confirmPhoneNumber) &&
    confirmPhoneNumber === phoneNumber){
      Toast({
        message:"注销成功，感谢您的使用",

      })
      setTimeout(()=>{
        wx.reLaunch({
          url: '/pages/login/index',
        })
      },2000)
    }else{
      Toast({
        message:"输入有误，请重新输入"
      })
    }
  }
})